package com.shuqi.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.shuqi.activity.adapter.LoginAccountAdapter;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.SyncBookMarks;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.RegexUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.LoginAcountController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.AccountLoginHistoryInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.LoginAccountParser.LoginAccountParserInfo;
import com.shuqi.model.sharedprefs.SpLoginHistory;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;
import com.shuqi.third.FunctionListener;
import com.shuqi.third.SinaFunction;

public class LoginActivity extends ActivityBase implements OnClickListener, OnFocusChangeListener,
        IEventListener {
    private static final String logTag = "LoginActivity";
    /** Intent Key： 传递登录类型 */
    private static final String INTENT_KEY_INT_LOAGINTYPE = "loginType";
    /** Intent Key： 传递是否显示注册 */
    private static final String INTENT_KEY_BOOLEAN_SHOWREGISTER = "showRegister";
    /** Intent Key： 打开登录页动作 */
    private static final String INTENT_KEY_INT_ACTION = "action";
    
    /** 登录类型：正常登录 */
    public static final int LOGINTYPE_LOGIN = 200;
    /** 登录类型：验证登录 */
    public static final int LOGINTYPE_VERIFY = 201;
    
    /** 当前登录的类型：正常登录/验证登录 */
    private int mLoginType = LOGINTYPE_LOGIN;

    /** 打开登陆页的动作类型：注册完成 */
    public static final int ACTION_REGISTER_OK = 300;
    
    private View mAccountView;
    private View mPasswordView;
    private TextView mAccountPoint;
    private TextView mPasswordPoint;
    private TextView mLoginRegister = null;
    private TextView mFindPasswordTextView = null;
    private EditText mAccountNameEditText = null;
    private EditText mAccountPasswordEditText = null;
    private TextView mCompleteTextView = null;
    private ImageView mImgPasswordVis = null;
    private ImageView mImgAccountNamePullImg = null;
    public List<AccountLoginHistoryInfo> mLoginHistoryList = new ArrayList<AccountLoginHistoryInfo>();// 登录历史的list
    private LoginAcountController mLoginAcountController;
    private LoginHandler mHandler;
    private LoginAccountAdapter mLoginHistoryAdapter;

    private PopupWindow mLoginListPopupWindow;// 登录历史展示的PopupWindow

    private boolean mIsHidePopupWindow = false;
    private boolean mIsHidePassword = true;

    private ToastDialog mLoginDialog;
    
    private String mEditeTestLoginAccountName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login_shuqi);
        mLoginAcountController =
                (LoginAcountController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_LOGIN_ACCOUNT, this);
        boolean isShowRegister = false;
        // 登录类型：验证还是登录
        Intent intent = getIntent();
        if (intent != null) {
            mLoginType = intent.getIntExtra(INTENT_KEY_INT_LOAGINTYPE, LOGINTYPE_LOGIN);
            isShowRegister = intent.getBooleanExtra(INTENT_KEY_BOOLEAN_SHOWREGISTER, false);
        }
        mLoginAcountController.addEventListener(this);
        mHandler = new LoginHandler(this);
        initAccountData();
        initView(isShowRegister);
    }

    private void initAccountData() {
        mLoginHistoryList = SpLoginHistory.getInstance().getAllLoginHistory();
    }

    private void initView(boolean isShowRegister) {
        mAccountView = findViewById(R.id.layout_account);
        mPasswordView = findViewById(R.id.layout_pwd);
        mAccountPoint = (TextView) findViewById(R.id.account_point);
        mPasswordPoint = (TextView) findViewById(R.id.pwd_point);
        mLoginRegister = (TextView) findViewById(R.id.account_login_register);
        mFindPasswordTextView = (TextView) findViewById(R.id.login_title_right_text);
        mAccountNameEditText = (EditText) findViewById(R.id.edit_account);
        mAccountPasswordEditText = (EditText) findViewById(R.id.edit_password);
        mCompleteTextView = (TextView) findViewById(R.id.complete_ok);
        mImgPasswordVis = (ImageView) findViewById(R.id.img_visible);
        mImgAccountNamePullImg = (ImageView) findViewById(R.id.img_pullDown);

        Boolean isGuestUser =
                MyAccountManager.isGuestUser(MyAccountManager.getInstance(getApplicationContext()));
        Log4an.i(logTag, "isGuestUser:"+isGuestUser+",mLoginType="+(mLoginType == LOGINTYPE_LOGIN?"正常登录":"验证登录"));
        if (isGuestUser || isShowRegister) {
            mLoginRegister.setVisibility(View.VISIBLE);
            mLoginRegister.setOnClickListener(this);
        } else {
            mLoginRegister.setVisibility(View.GONE);
            StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_LOGIN_VERIFY_PAGE_ENTER);
        }
        mFindPasswordTextView.setOnClickListener(this);
        mCompleteTextView.setOnClickListener(this);
        mImgPasswordVis.setOnClickListener(this);
        mAccountPasswordEditText.setOnFocusChangeListener(this);

        mImgAccountNamePullImg.setOnClickListener(this);
        findViewById(R.id.title_left).setOnClickListener(this);
        findViewById(R.id.login_with_sina).setOnClickListener(this);

        mAccountNameEditText.setOnClickListener(this);
        mAccountNameEditText.setOnFocusChangeListener(this);

        mAccountView.setSelected(true);
        mPasswordView.setSelected(false);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    private void newLoginListPopupWindow() {
        View popupView = getLayoutInflater().inflate(R.layout.login_history_popupwindow, null);
        ListView loginListView =
                (ListView) popupView.findViewById(R.id.login_history_popwindow_listView);
        mLoginHistoryAdapter = new LoginAccountAdapter(mLoginHistoryList, mHandler);
        loginListView.setAdapter(mLoginHistoryAdapter);
        mLoginListPopupWindow =
                new PopupWindow(popupView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
                        true);
        mLoginListPopupWindow.setTouchable(true);
        mLoginListPopupWindow.setOutsideTouchable(true);
        mLoginListPopupWindow.setFocusable(false);
        mLoginListPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),
                (Bitmap) null));
        mLoginListPopupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                changeUpView(false);
            }
        });
        mLoginListPopupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Rect mRectSrc = new Rect();
                mImgAccountNamePullImg.getGlobalVisibleRect(mRectSrc);
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE
                        && mLoginListPopupWindow != null && mLoginListPopupWindow.isShowing()
                        && mRectSrc.contains((int) event.getRawX(), (int) event.getRawY())) {
                    mIsHidePopupWindow = true;
                }

                return false;
            }
        });
    }

    private void showPopupWindow() {
        if (mLoginListPopupWindow == null) {
            newLoginListPopupWindow();
        }
        if (mLoginListPopupWindow != null) {
            mLoginListPopupWindow.showAsDropDown(mAccountNameEditText, 0,
                    Util.dip2px(getApplicationContext(), 10));
        }
    }

    private void hidePopupWindow() {
        if (mLoginListPopupWindow != null) {
            mLoginListPopupWindow.dismiss();
        }
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left: {
                setResult(Activity.RESULT_CANCELED);
                ActivityManager.getInstance().bottomFinishActivity(this);
            }
                break;
            case R.id.login_title_right_text: {
                if (mLoginType == LOGINTYPE_LOGIN) {
                    StatisticsUtils
                            .onEvent(StatisticsEventID.ACCOUNT_LOGIN_NORMAL_PAGE_FINDPASSWORD_CLICK);
                } else if (mLoginType == LOGINTYPE_VERIFY) {
                    StatisticsUtils
                            .onEvent(StatisticsEventID.ACCOUNT_LOGIN_VERIFY_PAGE_FINDPASSWORD_CLICK);
                }
                // 跳转
                FindPasswordActivity.show(this);
            }
                break;
            case R.id.complete_ok: {
                String mPassword = mAccountPasswordEditText.getText().toString().trim();
                String mAccount = mAccountNameEditText.getText().toString().trim();
                if (checkAccountInput(mAccount) && checkPasswordInput(mPassword)) {
                    mEditeTestLoginAccountName = mAccount;
                    showLoginDialog();
                    mLoginAcountController.handle(LoginAcountController.LOGIN_ACCOUNT_DEFAULT,
                            mAccount, mPassword);
                    if (mLoginType == LOGINTYPE_LOGIN) {
                        StatisticsUtils
                                .onEvent(StatisticsEventID.ACCOUNT_LOGIN_NORMAL_PAGE_LOGIN_CLICK);
                    } else if (mLoginType == LOGINTYPE_VERIFY) {
                        StatisticsUtils
                                .onEvent(StatisticsEventID.ACCOUNT_LOGIN_VERIFY_PAGE_LOGIN_CLICK);
                    }
                }
            }
                break;
            case R.id.img_visible: {
                changePasswordDisMode();
            }
                break;
            case R.id.img_pullDown:
                if (mIsHidePopupWindow) {
                    mIsHidePopupWindow = false;
                    return;
                }
                if (mLoginHistoryList != null && mLoginHistoryList.size() > 0) {
                    changeUpView(true);
                }
                break;
            case R.id.account_login_register:
                //产品取消邮箱注册，快速注册直接到手机注册页面
                StatisticsUtils.onEvent(LoginActivity.this, StatisticsEventID.ACCOUNT_FAST_RIGISTER);
//                Intent intent = new Intent(LoginActivity.this, FastRegisterActivity.class);
//                ActivityManager.getInstance().startNextActivity(intent, this);
//                StatisticsUtils.onEvent(LoginActivity.this,StatisticsEventID.ACCOUNT_MOBLE_RIGISTER);
                Intent intent = new Intent(LoginActivity.this, MobileRegisterActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                break;
            case R.id.login_with_sina:
                if (mLoginType == LOGINTYPE_LOGIN) {
                    StatisticsUtils
                            .onEvent(StatisticsEventID.ACCOUNT_LOGIN_NORMAL_PAGE_LOGIN_BYSINA_CLICK);
                } else if (mLoginType == LOGINTYPE_VERIFY) {
                    StatisticsUtils
                            .onEvent(StatisticsEventID.ACCOUNT_LOGIN_VERIFY_PAGE_LOGIN_BYSINA_CLICK);
                }
                loginBySina();
                break;
            default:
                break;
        }
    }

    /** 检查密码输入 */
    private boolean checkPasswordInput(String mPassword){
        boolean checkPassed = false;
        if (TextUtils.isEmpty(mPassword) || TextUtils.isEmpty(mPassword.trim())) {
            // 密码为空
            checkPassed = false;
            showTips(mPasswordPoint,
                    getString(R.string.account_login_account_password_empty), true);
        } else if (mPassword.trim().length() < 6) {
            checkPassed = false;
            showTips(mPasswordPoint, getString(R.string.password_too_short), true);
        } else if (mPassword.trim().length() > 16) {
            checkPassed = false;
            showTips(mPasswordPoint, getString(R.string.password_too_long), true);
        } else {
            checkPassed = true;
            mPasswordPoint.setVisibility(View.INVISIBLE);
        }
        return checkPassed;
    }
    
    /** 检查邮箱输入 */
    private boolean checkAccountInput(String mAccount){
        boolean checkPassed = false;
        if (TextUtils.isEmpty(mAccount) || TextUtils.isEmpty(mAccount.trim())) {
            // 账户名为空
            checkPassed = false;
            showTips(mAccountPoint, getString(R.string.account_login_account_name_empty),
                    true);
        } else if (!RegexUtil.isEmail(mAccount.trim())
                && !RegexUtil.isMobileNO(mAccount.trim())) {
            // 账户名格式错误
            checkPassed = false;
            showTips(mAccountPoint,
                    getString(R.string.account_login_input_correct_account), true);
        } else {
            checkPassed = true;
            mAccountPoint.setVisibility(View.INVISIBLE);
        }
        return checkPassed;
    }
    
    /** 账号/密码提示 */
    private void showTips(TextView textView, String tips, boolean isError) {
        if (textView != null && !TextUtils.isEmpty(tips)) {
            textView.setVisibility(View.VISIBLE);
            textView.setTextColor(getResources().getColor(isError?R.color.hint_error_color:R.color.hint_color));
            textView.setText(tips);
        }
    }

    // 改变账号下拉，上拉状态
    private void changeUpView(boolean isShowUp) {
        if (isShowUp) {
            mImgAccountNamePullImg.setImageResource(R.drawable.login_account_up);
            showPopupWindow();
        } else {
            mImgAccountNamePullImg.setImageResource(R.drawable.login_account_drop_down);
        }
    }

    private void changePasswordDisMode() {
        // 是否明文显示密码
        if (mIsHidePassword) {
            mIsHidePassword = false;
            mImgPasswordVis.setImageResource(R.drawable.password_visible);
            mAccountPasswordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//            mAccountPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | 
//                    InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            if (!TextUtils.isEmpty(mAccountPasswordEditText.getText().toString())) {
                mAccountPasswordEditText.setSelection(mAccountPasswordEditText.getText().toString()
                        .length());
            }

        } else {
            mIsHidePassword = true;
            mImgPasswordVis.setImageResource(R.drawable.password_invisible);
            mAccountPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
//            mAccountPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | 
//                    InputType.TYPE_TEXT_VARIATION_PASSWORD);
            if (!TextUtils.isEmpty(mAccountPasswordEditText.getText().toString())) {
                mAccountPasswordEditText.setSelection(mAccountPasswordEditText.getText().toString()
                        .length());
            }
        }
    }



    private void showLoginDialog() {
        if (mLoginDialog == null) {
            mLoginDialog = new ToastDialog(this);
            mLoginDialog.setDissmisOnClickOutSide(false);
        }
        mLoginDialog.loading("登录中，请稍候...");
    }

    private void hideLoginDailog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoginDialog != null) {
                    mLoginDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);

    }

    /**
     * 
     * @param info 存入最新的用户信息
     */
    private void loginSuccess(LoginAccountParserInfo info) {
        UserInfo user = new UserInfo();
        user.setUserId(info.uid);
        user.setEmail(info.email);
        user.setMobile(info.mobile);
        user.setNickName(info.nickname);
        user.setSinaName(info.sinanickname);
        user.setSinaKey(info.sinaId);
        user.setSession(info.session);
        MyAccountManager.onLoginSuccess(getApplicationContext(), user);

        // 同步书签
        UserInfo userInfo = MyAccountManager.getInstance(ShuqiApplication.getContext());
        SyncBookMarks.syncBookMarks(ShuqiApplication.getContext(), userInfo, null,"yes");

        //保存登录历史
        if(!TextUtils.isEmpty(mEditeTestLoginAccountName)){
            if(mEditeTestLoginAccountName.equals(info.email) || mEditeTestLoginAccountName.equals(info.mobile)){
                SpLoginHistory.getInstance().saveLoginAcoount(mEditeTestLoginAccountName);
            }
        }
    }

    private SinaLogin mSinaLogin = new SinaLogin(this);

    private void loginBySina() {
        SinaFunction.login(this, false, mSinaLogin);
    }

    @Override
    public void onEvent(int event, final Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                onNetCallback(data);
                break;
            case EventTypeConstants.EVENT_EXC_PARSER:
                hideLoginDailog();
                showMsg("解析异常");
                break;
            default:
                hideLoginDailog();
                showMsg("网络异常");
                break;
        }
    }

    private void onNetCallback(final Object data) {
        if (data != null && data instanceof LoginAccountParserInfo) {
            ShuqiApplication.getApplicationHandler().post(new Runnable() {

                @Override
                public void run() {
                    hideLoginDailog();
                    LoginAccountParserInfo myData = (LoginAccountParserInfo) data;
                    final int status = myData.resultCode;
                    final String msg = myData.message;
                    if (!TextUtils.isEmpty(msg)) {
                        showMsg(msg);
                    }
                    if (status == 100) {
                        loginSuccess(myData);
                        AccountActivity.callRefreshAccountOnResume();
                        if (mLoginType == LOGINTYPE_LOGIN) {
                            setResult(Activity.RESULT_OK);
                            AccountActivity.open(LoginActivity.this, true);
                        } else {
                            setResult(Activity.RESULT_OK);
                        }
                        ActivityManager.getInstance().bottomFinishActivity(LoginActivity.this);
                    }
                }
            });
        }
    }

    private void delAccount(AccountLoginHistoryInfo info) {
        if (mLoginHistoryList != null && mLoginHistoryList.contains(info)) {
            SpLoginHistory.getInstance().deleteLoginHistory(info.getLoginAccount());
            mLoginHistoryList.remove(info);
        }
        mLoginHistoryAdapter.notifyDataSetChanged();
        if (mLoginHistoryList == null || mLoginHistoryList.size() == 0) {
            changeUpView(false);
        }
    }

    private void loginAccount(AccountLoginHistoryInfo info) {
        String account = info.getLoginAccount();
        hidePopupWindow();
        mAccountNameEditText.setText(account);
        mAccountNameEditText.setSelection(account.length());
        changeUpView(false); 
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view.getId() == R.id.edit_account) {
//            if (hasFocus && mLoginHistoryList != null && mLoginHistoryList.size() > 0) {
//                changeUpView(true);
//            }
            mAccountView.setSelected(hasFocus);
        }else if (view.getId() == R.id.edit_password) {
            mPasswordView.setSelected(hasFocus);
            if(hasFocus){
                checkAccountInput(mAccountNameEditText.getText().toString().trim());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.hidesoftkeyboard(this, mAccountNameEditText);
        if (mLoginListPopupWindow != null) {
            mLoginListPopupWindow.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLoginAcountController.onDestroy();
        hideLoginDailog();
    }

    /** 正常打开登录：登录完成后去登陆页 */
    public static void openLogin(Activity activity) {
        Log4an.e(logTag, "正常登录页：来自："+activity.getClass().getSimpleName());
        openLoginActivity(activity, LOGINTYPE_LOGIN, false, -1);
    }
    /** 正常打开登录：登录完成后去登陆页 */
    public static void openLoginForResult(Activity activity,int requestCode) {
        Log4an.e(logTag, "正常登录页：来自："+activity.getClass().getSimpleName());
        openLoginActivity(activity, LOGINTYPE_LOGIN, true, requestCode);
    }

    /** 需要验证用户登录时登录：登录完成后去账户页 */
    public static void openVerifyForResult(Activity activity, int requestCode) {
        Log4an.e(logTag, "验证登录页：来自："+activity.getClass().getSimpleName()+", requestCode="+requestCode);
//        openLoginActivity(activity, LOGINTYPE_VERIFY, requestCode);
        openLoginActivity(activity, LOGINTYPE_LOGIN, true, -1);
    }
    
    /** 需要验证用户登录时登录：登录完成后back */
    public static void openVerifyLoginForResultAndBack(Activity activity, int requestCode) {
        Log4an.e(logTag, "验证登录页：来自："+activity.getClass().getSimpleName()+", requestCode="+requestCode);
        openLoginActivity(activity, LOGINTYPE_VERIFY, true, requestCode);
    }
    
    /** 本地未验证通过时：验证用户登录：登录完成后关闭自己，不做任何跳转 */
    public static void openLoginVerifyForResult(Activity activity) {
        Log4an.e(logTag, "验证登录页：来自："+activity.getClass().getSimpleName());
        openLoginActivity(activity, LOGINTYPE_VERIFY, true, -1);
    }
    
    /**
     * 打开登陆页
     * 
     * @param activity
     * @param loginType 登录类型：正常登录/验证登录
     * @param requestCode
     */
    private static void openLoginActivity(Activity activity, int loginType,boolean isShowRegister, int requestCode) {
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(INTENT_KEY_INT_LOAGINTYPE, loginType);
        intent.putExtra(INTENT_KEY_BOOLEAN_SHOWREGISTER, isShowRegister);
        ActivityManager.getInstance().startBottomNextActivityForResult(intent, requestCode,
                activity);
    }
    
    /**注册成功，关掉登陆页*/
    public static void finishLoginAfterRegistOk(Activity context){
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(INTENT_KEY_INT_ACTION, ACTION_REGISTER_OK);
        ActivityManager.getInstance().startNextActivity(intent, context);
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        Log4an.i(logTag, "onNewIntent()");
        super.onNewIntent(intent);
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            if(intent.getIntExtra(INTENT_KEY_INT_ACTION, -1) == ACTION_REGISTER_OK){
//                Log4an.i(logTag, "onNewIntent() 注册完成，关闭自己");
//                setResult(Activity.RESULT_OK);
                ActivityManager.getInstance().bottomFinishActivity(this);
                Log4an.i(logTag, "onNewIntent() 注册完成，到我的账户页");
                AccountActivity.open(this, true);
            }
        }
    }

    // handler 处理
    public static class LoginHandler extends Handler {

        public final static int LOGINHANDLER_DEL_ACCOUNT = 100;

        public final static int LOGINHANDLER_LOGIN_ACCOUNT = 200;

        WeakReference<LoginActivity> ref;

        public LoginHandler(LoginActivity activity) {
            ref = new WeakReference<LoginActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (ref == null || ref.get() == null || ref.get().isFinishing()) {
                return;
            }
            switch (msg.what) {
                case LOGINHANDLER_DEL_ACCOUNT:
                    AccountLoginHistoryInfo delinfo = (AccountLoginHistoryInfo) msg.obj;
                    ref.get().delAccount(delinfo);
                    break;
                case LOGINHANDLER_LOGIN_ACCOUNT:
                    AccountLoginHistoryInfo loginfo = (AccountLoginHistoryInfo) msg.obj;
                    ref.get().loginAccount(loginfo);
                    break;
                default:
                    break;
            }
        }
    }

    /** 新浪登录功能 */
    public static class SinaLogin implements FunctionListener {
        WeakReference<LoginActivity> ref;

        public SinaLogin(LoginActivity activity) {
            ref = new WeakReference<LoginActivity>(activity);
        }

        private boolean isActivityActive() {
            return ref != null && ref.get() != null && !ref.get().isFinishing();
        }

        @Override
        public void onComplete(final String uid) {
            if (!isActivityActive()) {
                return;
            }
            // sina 返回结果 接着登录我们的接口
            ShuqiApplication.getApplicationHandler().post(new Runnable() {

                @Override
                public void run() {
                    if (!isActivityActive()) {
                        return;
                    }
                    ref.get().showLoginDialog();
                    ref.get().mLoginAcountController.handle(
                            LoginAcountController.LOGIN_ACCOUNT_SINA, uid);
                }
            });
        }

        @Override
        public void onError() {
            if (!isActivityActive()) {
                return;
            }
            ref.get().hideLoginDailog();
            ref.get().showMsg("新浪微博连接失败");
        }

        @Override
        public void onShow(String name, String uid) {}
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().bottomFinishActivity(this);
            setResult(Activity.RESULT_CANCELED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
